package com.xinsoft.jwt;

import com.github.pagehelper.util.StringUtil;
import com.xinsoft.entity.dto.SysUserDetail;
import com.xinsoft.utils.RedisUtil;
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.stereotype.Component;
import org.springframework.web.filter.OncePerRequestFilter;

import javax.annotation.Resource;
import javax.servlet.FilterChain;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.Map;

/**
 * @author hsm
 * @description JWT过滤器
 * @createDate 2023-04-24
 */
@Component
public class JwtAuthenticationTokenFilter extends OncePerRequestFilter {

    @Resource
    private JwtTokenUtil jwtTokenUtil;

    @Resource
    private RedisUtil redisUtil;

    @Override
    protected void doFilterInternal(HttpServletRequest request,
                                    HttpServletResponse response,
                                    FilterChain filterChain)
            throws ServletException, IOException {
        String jwtToken = request.getHeader(jwtTokenUtil.getHeader());
        if(StringUtil.isNotEmpty(jwtToken)){
            String username = jwtTokenUtil.getUsernameFromToken(jwtToken);

            if(username != null && SecurityContextHolder.getContext().getAuthentication() == null){

                Map<Object, Object> userMap = redisUtil.hmget(jwtToken);
                String uname = (String) userMap.get("userName");

                SysUserDetail userDetails = new SysUserDetail();
                userDetails.setUsername(uname);

                if(jwtTokenUtil.validateToken(jwtToken,userDetails)){

                    UsernamePasswordAuthenticationToken authenticationToken
                            = new UsernamePasswordAuthenticationToken(userDetails,null,
                            userDetails.getAuthorities());
                    SecurityContextHolder.getContext().setAuthentication(authenticationToken);

                }
            }
        }
        filterChain.doFilter(request,response);
    }
}